Flash Article

Creating Movie Clip Subclasses in ActionScript 2.0


Table of Contents

  1. Introduction
  2. Classes and Objects, Symbols and Clips
  3. A Short History of Movie Clip Behaviors
  4. Tutorial 1: Using a Movie Clip Subclass to Make a Bouncing Ball Animation
  5. Tutorial 2: Creating a More Extensive Grab-and-Match Puzzle

Tutorial 2: Creating a More Extensive Grab-and-Match Puzzle

Watching balls bounce around the Stage (even if each one is a little different) isn't that exciting—at least not for very long. This tutorial uses the same techniques demonstrated in the previous tutorial but takes them a little farther to create a simple game. In this game, the player must capture a puzzle piece shape that's bouncing around one area and drag it to the identical white shape in another area. You can play the game (and download the tutorial's FLA and class files from the first page).

This game is slightly more elaborate than the one originally presented in the ActionScript 1.0 version of this article. It uses a more object-oriented approach, changes the color of the piece when a player successfully grabs it, randomizes the position of each piece in the drop zone area, and lets the player quit without completing the entire game.

In order to minimize the size of the SWF file, I only created one graphic symbol for each shape. The shapes are loaded dynamically into two different types of movie clips when the clips are attached to the Stage. The PuzzlePiece movie clip provides the drag-and-drop and bouncing-around behaviors. The DropZone movie clip is a convenient target movie clip. Each PuzzlePiece clip has a matching DropZone clip containing the same shape on which the player must drop it. If you look at these two movie clips in the library, you see that they are really just empty movie clips; they contain no code or graphics. In fact, the only reason they are in the library at all is so that there will be movie clips available with the PuzzlePiece and DropZone linkage identifiers. The appearance of these clips comes from attaching graphic symbols to the movie clips when each movie clip is attached to the movie. The event handlers for the movie clip come from the ActionScript in the class files for the PuzzlePiece and DropZone classes.

The symbols in the library are simple, single-layer graphics drawn in white and named pGraphic1, pGraphic2, and so on. Each one has a linkage identifier in the same format. You can find them all in the Graphics folder in the library.

There are two other movie clips worth mentioning here. One is a simple white rectangle movie clip manually placed on the Stage and given the instance name bounceBox. This clip defines the area in which the PuzzlePiece movie clips are allowed to bounce around. The DropBar movie clip was also manually placed on the Stage to provide a black background area for the white DropZone clips.

The DropZone Movie Clips

If you look at the DropZone movie clip in the library you see that it contains no graphics or script. The clip gets its appearance and behaviors by executing methods of the ActionScript DropZone class defined in the DropZone.as file. If you check the linkage properties of the DropZone movie clip in the library you'll see something like Figure 3.

The DropZone movie clip is associated with the DropZone class.

Figure 3. The DropZone movie clip is associated with the DropZone class.

Each DropZone clip acts as a target clip for one of the PuzzlePiece clips. When a DropZone clip is attached to the movie (using the global attachMovie() function) it is passed a number that it uses to attach the right pGraphic symbol from the library to itself. A matching PuzzlePiece is given the same number and uses the same graphic. Note that the attachMovie() method of the movie clip attaches the pGraphic to the clip, not the global attachMovie() function. Calling attachMovie() within a MovieClip subclass definition calls the attachMovie method; you don't need to prepend this to it. Doing this loads that graphic into the DropZone movie clip rather than into the movie. The movie clip's method is called, instead of the global function, because attachMovie() is being called from within the DropZone class.

Here is the complete code for the DropZone class. Please take a minute to read through it:

dynamic class DropZone extends MovieClip {

   // Parameter passed in by attachMovie in the initObject.
   var gNumber:Number;
   
   /**
    * The DropZone constructor gets one of the graphics from the library named 
    * pGraphic1 through pGraphic13 and attaches it to this movie clip.
    */
   function DropZone() {
      attachMovie("pGraphic" + gNumber, "graphic" , 100);     
   }
   
   /**
    * The fadeOut method is called when a matching Puzzle Piece is dropped 
    * on this DropZone clip and calls this clip's fadeOut() method.
    * fadeOut sets the onEnterFrame handler for this clip to an anonymous function 
    * that fades out the clip and then removes it altogether once it 
    * is transparent.
    */
   function fadeOut() {
      onEnterFrame = function () {
         _alpha -= 10;
         if (_alpha <= 0) {
            removeMovieClip(this);
         }
      };
   }
}

The DropZone class is not long and complex. Aside from attaching the right shape symbol in the library in order to give itself a visible shape, it only includes one method. A PuzzlePiece clip calls the DropZone's fadeOut() method if it discovers that the player has dropped it on its target DropZone clip. Just as with the earlier Ball class, the DropZone class extends the MovieClip class so that it can be tied to a DropZone clip instance on the Stage, manipulate movie clip properties, and receive movie clip events.

The Puzzle Pieces

The PuzzlePiece movie symbol is also an empty clip in the library. Each PuzzlePiece clip on the Stage gets its appearance and behavior by executing code that's part of the PuzzlePiece class definition in the PuzzlePiece.as file. The PuzzlePiece class is the most complicated class in the game but when you look at the code you see that it is similar in many respects to the Ball class from the previous tutorial. Like the Ball class, the PuzzlePiece class constructor does the following:

  • It determines the travel limits of the puzzle piece, but this time within a bounceBox movie clip. A reference to the bounceBox clip is passed into the PuzzlePiece constructor in an initObject.
  • It determines an initial random position within the bounceBox and a random direction and velocity in which to travel.

Like the Ball class, the onEnterFrame() method of the PuzzlePiece class moves the puzzle piece inside the bounceBox clip.

The PuzzlePiece class is different than the Ball class because it allows the player to drag the clip around the Stage. If the player drops the clip on top of the matching DropZone, the PuzzlePiece tells the matching DropZone clip to fade out, tells the scoreKeeper object to count a hit, and then disposes of itself. The matching DropZone clip and scoreKeeper objects must be passed into each PuzzlePiece in an initObject when the PuzzlePiece is attached to the movie. The code that does this is shown later.

Here is the complete code for the PuzzlePiece class. Please spend a few minutes reading through it (it's been extensively commented):

/**
 * The PuzzlePiece class provides all the prebuilt behaviors and 
 * additional properties needed by a PuzzlePiece movie clip to:
 *   1. Position itself randomly within a the bounceBox movie clip 
 *      and move randomly within it.
 *   2. Allow the clip to be dragged around the stage.
 *   3. Detect if it has been dropped on its targetClip and tell the 
 *      scoreKeeper object if it has.
 *
 * This class is designed for use when the PuzzlePiece clip is attached 
 * to the movie by calling attachMovie and must be passed the following 
 * parameters in the initObject:
 *   1. bounceBox – a reference to a movie clip that this clip must bounce within.
 *   2. gNumber – the number of the graphic in the library to load into this clip.
 *   3. targetClip – a DropZone clip this clip is supposed to be dropped on.
 *   4. scoreKeeper – a reference to an ActionScript object so this clip can 
 *      report that it has been dropped on its targetClip.
 *
 * Version: 2
 * Author: Brian Lesser
 */

dynamic class PuzzlePiece extends MovieClip {
   /////// Properties of this movie clip subclass 
   // Color object used to change the color of this clip's graphic:
   var gColor:Color;
   // Travel limits in x and y for this clip's registration point:
   var xMin:Number, xMax:Number, yMin:Number, yMax:Number;
   // x and y velocity (number of pixels to move in x and y between frames):
   var xVel:Number, yVel:Number;
   // Flag to keep track if the clip is being dragged:
   var dragging:Boolean = false;
   
   /////// Properties of this movie clip subclass 
   /////// passed in from the initObject.
   // Movie clip that defines the travel limits of the clip when bouncing around:
   var bounceBox:MovieClip; 
   // Graphic number in the library of the graphic to load into this clip:
   var gNumber:Number;
   // Target clip that this clip should be dropped on:
   var targetClip:MovieClip;
   // The score keeper object that records hits:
   var scoreKeeper:ScoreKeeper;

   /**
    * The PuzzlePiece Constructor sets up the clip's appearance, travel limits,
    * initial position and velocity.
    */
   function PuzzlePiece() {
      //Attach the graphic shape to this clip:
      var graphic = attachMovie("pGraphic" + gNumber, 'graphic', 100);
   
      //Make everything a grey/blue color to start:
      gColor = new Color(graphic);
      gColor.setRGB(0x443377); 
      
      // Determine the bounding limits for the registration point 
      // within the bounceBox clip:
      var halfWidth  = _width/2;
      var halfHeight = _height/2;
      xMin = bounceBox._x + halfWidth;
      yMin = bounceBox._y + halfHeight;
      xMax = xMin + bounceBox._width  – _width;
      yMax = yMin + bounceBox._height – _height;  
      
      //Select a random position within the bounceBox clip to show up in:
      _x = Math.floor(Math.random() * (xMax – xMin) + xMin);
      _y = Math.floor(Math.random() * (yMax – yMin) + yMin);
      
      //Select a random direction to start moving this clip in.
      xVel = Math.floor(Math.random() * 12) – 5;
      yVel = Math.floor(Math.random() * 12) – 5;
      
      // Dynamically make the onReleaseOuside method the same as the 
      // onRelease method.
      onReleaseOutside = onRelease;      
   }
   
   /** 
    * The onPress method is a movie clip event handler that is called 
    * whenever the user on this clip with the mouse. The method 
    * starts the dragging process so the clip will follow the mouse 
    * and adjusts its color.
    */
   function onPress() {
      startDrag(true);
      dragging = true;
      // Make the clip black to show it has been captured.
      gColor.setRGB(0x000000); 
   }
   
   /**
    * The onEnterFrame method is called whenever an EnterFrame
    * event is sent to this movie clip subclass. If the clip is not 
    * being dragged, the next position of the clip is calculated
    * making sure to keep it within bounds and then the clip
    * is moved to that position.
    */
   function onEnterFrame() {
      if (dragging) 
         return;
      }
      var nextX = _x + xVel;
      var nextY = _y + yVel;
      if (nextX < xMin) {
         xVel *= –1;
         nextX = xMin + (xMin – nextX);
      } else if (nextX > xMax) {
         xVel *= –1;
         nextX = xMax – (nextX – xMax);
      }
      if (nextY < yMin) {
         yVel *= –1;
         nextY = yMin + (yMin – nextY);
      } else if (nextY > yMax) {
         yVel *= –1;
         nextY = yMax – (nextY – yMax);
      }
      _x = nextX;
      _y = nextY;
   }
   
   /**
    * When the player releases the mouse button this movie clip event 
    * handler is called. If the clip is dropped on its target clip
    * a hit is recorded using the scoreKeeper object and the puzzle 
    * piece disposes of itself. Otherwise the puzzle piece goes back
    * to moving inside the bounceBox.
    */
   function onRelease() {
      stopDrag();
      if (hitTest(targetClip)) {
         targetClip.fadeOut();
         scoreKeeper.recordHit();
		 this.removeMovieClip(); // Compiler bug – must use this.
      } else {
         gColor.setRGB(0x443377); // Make the clip a grey/blue color.
         dragging = false;
      }
   }
}

Note: In the previous version of this tutorial, I used onMouseDown and onMouseUp events to see if the player clicked or released the PuzzlePiece. This class uses the onPress, onRelease, and onReleaseOutside events instead, which simplifies the code.

Keeping Score

In the original version of this game, code on the movie Timeline kept track of the number of puzzle pieces that players successfully dropped on each drop zone as well as the time it took to play the game. In this version of the game, those functions now live inside an ActionScript class named ScoreKeeper. One scoreKeeper object is created at the start of a game and used to record successful puzzle piece drops and game time. Here is the complete code for the ScoreKeeper class. It's a simple class that does not extend any other class:

/**
 * The ScoreKeeper class is designed to keep track of how
 * long a game has taken to the play, and the number of 
 * successful hits. The recordHit method is called by PuzzlePiece
 * movie clips when they are dropped on the correct DropZone.
 * The constructor of this class must be passed:
 *   1. a reference to the timeline the game is on and
 *   2. the number of PuzzlePieces (or shapes) in the game.
 *
 * Version: 1
 * Author: Brian Lesser
 */

class ScoreKeeper{
   var hits:Number = 0;          // number of successful hits (puzzle piece drops)
   var nShapes:Number;           // number of Puzzle Pieces
   var startTime:Number;         // start time in milliseconds from getTimer()
   var endTime:Number;           // end time in milliseconds 
   var scoring:Boolean = true;   // flag that indicates if the game is being played
   var root:MovieClip;           // reference to the game timeline 
                                 // – normally level0 or _root
   
   /** ScoreKeeper constructor function */
   function ScoreKeeper(r, n){
      root = r;
      nShapes = n;
      startTime = getTimer();
   }
   
   /** 
    * recordHit is called to record a hit in the game. 
    * If the number of hits equals the number of shapes 
    * the game is over so the root movieclip reference is 
    * sent ahead to the EndGame frame.
    */
   function recordHit(){
      if (scoring) hits++;
      if (hits == nShapes){
         root.gotoAndPlay("EndGame");
      }
   }
   
   /** stopScoring gets the end time of the game and makes 
    *  further scoring impossible.
    */
   function stopScoring(){
      endTime = getTimer(); 
      scoring = false;
   }

   /** getScore returns a text string with the score in it.*/
   function getScore(){
      var totalTime = (endTime – startTime)/1000;
      // If they have placed all the pieces say thanks and tell them how long.
      if (hits == nShapes){
         return "Thanks for playing.\n\nIt took you " + 
                totalTime + 
                " seconds \nto play the game."
      }
      // If they didn't place all the pieces send a different message.
      else{
         var score = Math.round(hits/nShapes * 100);
         return "Thanks for playing.\n\nIt took you " + 
                totalTime + 
                " seconds \nto play " +  score + "% of the game."
      }
   }
}

Multiple States

So far every line of code in this tutorial has been part of a class definition. In fact, the vast majority of code appears in the three class files, PuzzlePiece.as, DropZone.as, and ScoreKeeper.as. The only other code in the game appears on the Actions layer of the main Timeline. This code handles the setup of the three states of the game. Each game state is associated with a label in the main Timeline (see Figure 4). The game is initialized on the Welcome frames, played on the PlayGame frames, and completed on the EndGame frames.

Each label in the movie Timeline label identifies a different state in the game.

Figure 4. Each label in the movie Timeline label identifies a different state in the game.

The unique code required for each state is on the first frame for that state in the Actions layer. To keep the playhead from running from one state to another, stop() is called once in each state. When the game must change state, a gotoAndPlay() is called.

The Welcome Frame: The welcome screen contains a text field with player instructions and a navigation button. It also contains the following code:

/**
 * fisher_yates_shuffle as adapted from the Perl Cookbook,
 * by Christiansen and Torkington, Published by O'Reilly
 * pass this array a reference to a function. For example:
 *    array = new Array('hi', 'bye', 'hello', 'goodbye');
 *    fisher_yates_shuffle(array);
 * and the function will pseudo randomize the elements of the
 * array in place.
 **/
function fisher_yates_shuffle(ar){
   var i, j 
   var temp
   for (i = ar.length – 1; i > 0; i––){
      j = Math.floor(Math.random() * (i + 1))
      if (i == j) continue
      temp = ar[i];
      ar[i] = ar[j];
      ar[j] = temp;
   }
}

// Create an arrray of shape numbers that can be randomized later
// in order to randomize the position of the shapes in the drop zone.
_global.shapeNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

// Initialize the navigation button.
label = "Start the Game!";
navButton.onRelease = function(){
   gotoAndPlay("PlayGame");
}

This code declares a global function to randomize the numbers in the shapeNumbers array and provides the navigation button with a label and code to execute if it is released. There isn't much to this code; the real action happens when the player presses the navButton and the playhead moves to the PlayGame frame.

The PlayGame Frame: Starting the game is the most complex part of the Timeline code. The complete code appears below. After a ScoreKeeper object is created to keep track of scoring, the game shapes themselves are randomly attached to the movie. To randomize the shapes, the numbers 1 through 13 are shuffled inside the shapeNumbers array. Following the shuffle the rest of the work is done inside a for loop. In each loop a DropZone clip is attached to the movie and passed one of the numbers in the array. Then a PuzzlePiece clip is attached and initialized with the same number. The DropZone clip is always created first so that a reference to it can be passed into the initObject of the PuzzlePiece clip. That is how each puzzle piece knows which drop zone it matches. Take a close look at the for loop in the code below to see how this works. Each DropZone clip is stored in the mc variable that is used later to initialize each PuzzlePiece. You may also want to check the ScoreKeeper constructor function again. Notice that it records the time when the game starts.

Aside from some variables to keep track of things, the important part of this code is the loop that creates the puzzle pieces and drop zones. Each puzzle piece is named p1, p2, p3 through p13 and each is given a number property with a value in the range of 1 to 13, which happens to be the same number of the graphic symbols in the library. There are also 13 DropZone movie clips created, named d1 through d13, with an initial _x and _y position and a number property that contains the number of the correct graphic symbol to load:

// Create a new score keeper object replacing the old one if one already exists.
_global.scoreKeeper = new ScoreKeeper(this, shapeNumbers.length);

// Shuffle the clip numbers in the shapeNumbers array so the clips
// are positioned randomly in the drop zone area.
fisher_yates_shuffle(shapeNumbers);

// Determine the _x position of the left-most clip
firstClipPosition = bounceBox_mc._x + 20;

var mc; // Variable to hold clip references.

// Create all the DropZone and PuzzlePiece clips in a loop.
for (i=0; i <shapeNumbers.length; i++){
   var gNumber = shapeNumbers[i];
   mc = attachMovie("DropZone", "d" + i, i + 200, 
                    {_x: i * 38 + firstClipPosition, 
                     _y: 336, 
                     gNumber: gNumber});
   attachMovie("PuzzlePiece",  "p" + i, i + 300, 
               {targetClip: mc, 
                bounceBox: bounceBox_mc, 
                gNumber:  gNumber, 
                scoreKeeper: scoreKeeper});
   
}

// Setup the navigation button.
label = "I Quit!";
navButton.onRelease = function(){
   // Remove any left over Puzzle Piece clips.
   for (var i = 0; i < shapeNumbers.length; i++){
      eval("p" + i).removeMovieClip();
   }
   gotoAndPlay("EndGame");
}

The EndGame Frame: The game can end in two ways. Each time a puzzle piece is dropped on its target drop zone it calls the scorekeeper.recordHit() method. If the scorekeeper determines that all the pieces have been used up it sends the game's playhead to the EndGame frame. Similarly, if the player presses the navButton in the PlayGame frames it sends the playhead to the EndGame frame. When the playhead arrives at the EndGame frame, the navButton is given a label "Play again!", the game is stopped by calling scoreKeeper.stopGame(), and an end-of-game message appears. Here is the complete code from the EndGame frame:

// Tell the score keeper the game is over.
scoreKeeper.stopScoring();

// Report the results to the user.
message_txt.text = scoreKeeper.getScore();

// Setup the navigation button for this frame of the movie.
label = "Play again!";
navButton.onRelease = function(){
   gotoAndPlay("PlayGame");
}

That's it to the grab-and-match puzzle. Go ahead, play the game. It's not as easy as it looks!

There is a nice parallel between movie clip symbols/instances and ActionScript classes/objects. Movie clip symbols in the library are much like ActionScript classes: They act as a template that defines the common characteristics of each movie clip. Movie clip instances are much like ActionScript objects: There can be many of them—each based on the original symbol—but with different characteristics, depending on how they were initialized and on what happens to them as the movie plays.

The difference between them is that ActionScript classes can provide predefined behaviors for ActionScript objects and, when those objects extend the MovieClip class, can also provide predefined behaviors for a movie clip symbol. Without ActionScript classes it is difficult to provide predefined behaviors in movie clip symbols.

Macromedia Flash MX first bridged the gap between these two parallel worlds. ActionScript 2.0 provides a simpler and more elegant way to write classes that extend movie clip symbols.